// 1. React核心库
import React, { useState, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Select, Space, message, Modal } from 'antd';

// 3. 图标库
import { 
  StarOutlined, 
  StarFilled, 
  UserOutlined, 
  RobotOutlined, 
  FileTextOutlined,
  SettingOutlined 
} from '@ant-design/icons';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { 
  AIConversation, 
  AIRole, 
  AIModel, 
  MessageTemplate 
} from '@/services/generated';

interface ChatControlBarProps {
  conversation: AIConversation | null;
  onConversationUpdate: (conversation: AIConversation) => void;
  onTemplateSelect: (template: MessageTemplate) => void;
}

const ChatControlBar: React.FC<ChatControlBarProps> = ({
  conversation,
  onConversationUpdate,
  onTemplateSelect,
}) => {
  // 状态管理
  const [roles, setRoles] = useState<AIRole[]>([]);
  const [models, setModels] = useState<AIModel[]>([]);
  const [templates, setTemplates] = useState<MessageTemplate[]>([]);
  const [isFavorited, setIsFavorited] = useState(false);
  const [templatesModalVisible, setTemplatesModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  // 获取角色列表
  const fetchRoles = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatRolesList({
        pageSize: 100,
      });
      setRoles(response.data?.items || []);
    } catch (error) {
      console.error('获取角色列表失败:', error);
    }
  };

  // 获取模型列表
  const fetchModels = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatModelsList({
        pageSize: 100,
      });
      setModels(response.data?.items || []);
    } catch (error) {
      console.error('获取模型列表失败:', error);
    }
  };

  // 获取消息模板列表
  const fetchTemplates = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatTemplatesList({
        pageSize: 100,
      });
      setTemplates(response.data?.items || []);
    } catch (error) {
      console.error('获取模板列表失败:', error);
    }
  };

  // 检查对话是否已收藏
  const checkConversationFavorited = async () => {
    if (!conversation?.id) return;
    
    try {
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatFavoritesList({
        pageSize: 100,
      });
      
      const favorited = response.data?.items?.some(
        favorite => favorite.conversation === conversation.id
      );
      setIsFavorited(!!favorited);
    } catch (error) {
      console.error('检查收藏状态失败:', error);
    }
  };

  // 更新对话角色
  const handleRoleChange = async (roleId: number) => {
    if (!conversation?.id) return;

    try {
      setLoading(true);
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatConversationsUpdate({
        id: String(conversation.id),
        aIConversationRequest: {
          ...conversation,
          ai_role: roleId,
        },
      });
      onConversationUpdate(response.data);
      message.success('角色切换成功');
    } catch (error) {
      message.error('角色切换失败');
    } finally {
      setLoading(false);
    }
  };

  // 更新对话模型
  const handleModelChange = async (modelId: number) => {
    if (!conversation?.id) return;

    try {
      setLoading(true);
      await autoLoginInDev();
      const response = await apiClients.aiChat.aiChatConversationsUpdate({
        id: String(conversation.id),
        aIConversationRequest: {
          ...conversation,
          ai_model: modelId,
        },
      });
      onConversationUpdate(response.data);
      message.success('模型切换成功');
    } catch (error) {
      message.error('模型切换失败');
    } finally {
      setLoading(false);
    }
  };

  // 收藏/取消收藏对话
  const handleToggleFavorite = async () => {
    if (!conversation?.id) return;

    try {
      setLoading(true);
      await autoLoginInDev();
      
      if (isFavorited) {
        // 取消收藏 - 需要先找到收藏记录ID
        const favoritesResponse = await apiClients.aiChat.aiChatFavoritesList({
          pageSize: 100,
        });
        const favoriteRecord = favoritesResponse.data?.items?.find(
          favorite => favorite.conversation === conversation.id
        );
        
        if (favoriteRecord?.id) {
          await apiClients.aiChat.aiChatFavoritesDestroy({
            id: String(favoriteRecord.id),
          });
          setIsFavorited(false);
          message.success('已取消收藏');
        }
      } else {
        // 添加收藏
        await apiClients.aiChat.aiChatFavoritesCreate({
          userFavoriteRequest: {
            title: conversation.title || '对话收藏',
            conversation: conversation.id,
            message: null,
            note: `收藏的对话: ${conversation.title}`,
          },
        });
        setIsFavorited(true);
        message.success('已收藏对话');
      }
    } catch (error) {
      message.error(isFavorited ? '取消收藏失败' : '收藏失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchRoles();
    fetchModels();
    fetchTemplates();
  }, []);

  // 监听对话变化
  useEffect(() => {
    if (conversation) {
      checkConversationFavorited();
    }
  }, [conversation]);

  if (!conversation) return null;

  return (
    <div style={{ 
      padding: '16px', 
      borderBottom: '1px solid #f0f0f0',
      backgroundColor: '#fafafa'
    }}>
      <Space wrap size="middle">
        {/* 角色选择 */}
        <Space>
          <UserOutlined />
          <span>角色:</span>
          <Select
            value={conversation.ai_role}
            onChange={handleRoleChange}
            loading={loading}
            style={{ width: 120 }}
            placeholder="选择角色"
          >
            {roles.map(role => (
              <Select.Option key={role.id} value={role.id}>
                {role.name}
              </Select.Option>
            ))}
          </Select>
        </Space>

        {/* 模型选择 */}
        <Space>
          <RobotOutlined />
          <span>模型:</span>
          <Select
            value={conversation.ai_model}
            onChange={handleModelChange}
            loading={loading}
            style={{ width: 120 }}
            placeholder="选择模型"
          >
            {models.map(model => (
              <Select.Option key={model.id} value={model.id}>
                {model.name}
              </Select.Option>
            ))}
          </Select>
        </Space>

        {/* 对话收藏按钮 */}
        <Button
          type={isFavorited ? "primary" : "default"}
          icon={isFavorited ? <StarFilled /> : <StarOutlined />}
          onClick={handleToggleFavorite}
          loading={loading}
        >
          {isFavorited ? '已收藏' : '收藏对话'}
        </Button>

        {/* 消息模板按钮 */}
        <Button
          icon={<FileTextOutlined />}
          onClick={() => setTemplatesModalVisible(true)}
        >
          消息模板
        </Button>
      </Space>

      {/* 消息模板选择Modal */}
      <Modal
        title="选择消息模板"
        open={templatesModalVisible}
        onCancel={() => setTemplatesModalVisible(false)}
        footer={null}
        width={600}
      >
        <div style={{ maxHeight: 400, overflowY: 'auto' }}>
          {templates.map(template => (
            <div
              key={template.id}
              style={{
                padding: '12px',
                border: '1px solid #f0f0f0',
                borderRadius: '6px',
                marginBottom: '8px',
                cursor: 'pointer',
                transition: 'all 0.2s',
              }}
              onClick={() => {
                onTemplateSelect(template);
                setTemplatesModalVisible(false);
                message.success(`已选择模板: ${template.name}`);
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = '#f5f5f5';
                e.currentTarget.style.borderColor = '#d9d9d9';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = 'white';
                e.currentTarget.style.borderColor = '#f0f0f0';
              }}
            >
              <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>
                {template.name}
              </div>
              {template.category && (
                <div style={{ color: '#666', fontSize: '12px', marginBottom: '8px' }}>
                  {template.category}
                </div>
              )}
              <div style={{ 
                color: '#999', 
                fontSize: '12px',
                maxHeight: '60px',
                overflow: 'hidden',
                textOverflow: 'ellipsis'
              }}>
                {template.content}
              </div>
            </div>
          ))}
        </div>
      </Modal>
    </div>
  );
};

export default ChatControlBar;